<template>
  <span class="vben-layout-header-action__item">
    <span>
      <Icon
        icon="ant-design:mail-outlined"
        v-if="is263EmailEnabled"
        @click="handleClickEmail()"
        title="邮箱"
        :size="iconSize"
      />
    </span>
  </span>
  <Dropdown placement="bottomLeft" :overlayClassName="`${prefixCls}-dropdown-overlay`">
    <span :class="[prefixCls, `${prefixCls}--${theme}`]" class="flex">
      <img :class="`${prefixCls}__header`" :src="getUserInfo.avatar" />
      <span :class="`${prefixCls}__info hidden md:block`">
        <span :class="`${prefixCls}__name  `" class="truncate">
          {{ getUserInfo.realName }}
        </span>
      </span>
    </span>
    <template #overlay>
      <Menu @click="handleMenuClick">
        <MenuItem
          key="doc"
          :text="t('layout.header.dropdownItemDoc')"
          icon="ion:document-text-outline"
          v-if="getShowDoc"
        />
        <MenuDivider v-if="getShowDoc" />
        <MenuItem key="person" text="个人信息" icon="ant-design:user-outlined" />
        <MenuItem key="mobile" text="修改手机" icon="ant-design:mobile-outlined" />
        <MenuItem key="pwd" text="修改密码" icon="ant-design:key-outlined" />
        <MenuItem
          key="role"
          text="切换角色"
          v-if="isRoleSwitchable"
          icon="ant-design:user-switch-outlined"
        />
        <MenuItem
          key="dept"
          text="切换部门"
          v-if="isDeptSwitchable"
          icon="ant-design:partition-outlined"
        />
        <MenuItem
          v-if="getUseLockPage"
          key="lock"
          :text="t('layout.header.tooltipLock')"
          icon="ion:lock-closed-outline"
        />
        <MenuItem
          key="logout"
          :text="t('layout.header.dropdownItemLoginOut')"
          icon="ion:power-outline"
        />
      </Menu>
    </template>
  </Dropdown>
  <span class="ml-2" v-if="isOnDutyEnabled">
    <Tag
      class="ml-2 cursor-pointer"
      v-if="getUserInfo.onDuty"
      color="success"
      @click="handleOnDuty()"
      >在岗</Tag
    >
    <Tooltip :title="formData.remark" v-if="!getUserInfo.onDuty">
      <Tag class="ml-2 cursor-pointer" color="warning" @click="handleOnDuty">离岗</Tag>
    </Tooltip>
  </span>
  <LockAction @register="register" />
  <PersonDrawer @register="registerPersonDrawer" @success="handlePersonCallback" />
  <ChangeCurDeptCodeModal @register="registerCurDeptCode" @success="handleCurDeptCodeCallback" />
  <CurRoleCodeModal @register="registerCurRoleCode" @success="handleCurRoleCodeCallback" />
  <ChangePwdModal @register="registerChangePwd" />
  <ChangeMobileModal @register="registerChangeMobile" />

  <Modal v-model:visible="onDutyVisible" title="设置在岗状态" :closable="true">
    <template #footer>
      <a-button @click="handleSubmit" type="primary">确定</a-button>
      <a-button @click="handleCancel">关闭</a-button>
    </template>
    <div style="padding: 20px">
      <Row>
        <Col :span="24">
          <Form :rules="rules" ref="formRef" :model="formData">
            <FormItem label="是否在岗" name="isOnDuty">
              <Switch
                v-model:checked="formData.isOnDuty"
                checked-children="是"
                un-checked-children="否"
              />
            </FormItem>
            <FormItem label="原因" v-if="!formData.isOnDuty" name="remark">
              <InputTextArea v-model:value="formData.remark" placeholder="请输入原因" />
            </FormItem>
          </Form>
        </Col>
        <Col :span="24" />
      </Row>
      <Row />
    </div>
  </Modal>
  <SmartModuleDrawer @register="registerDrawer" @success="handleSuccess" />
</template>
<script lang="ts">
  // components
  import {
    Dropdown,
    Menu,
    Tag,
    Modal,
    Row,
    Col,
    Form,
    Input,
    Switch,
    Tooltip,
  } from 'ant-design-vue';
  import Icon from '/@/components/Icon';
  import { defineComponent, computed, ref, unref, onMounted } from 'vue';
  import { DOC_URL } from '/@/settings/siteSetting';
  import { useUserStore } from '/@/store/modules/user';
  import { useHeaderSetting } from '/@/hooks/setting/useHeaderSetting';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useModal } from '/@/components/Modal';
  import { bufToUrl } from '/@/utils/file/base64Conver';
  import { onDuty } from '/@/api/sys/user';
  import type { Rule } from 'ant-design-vue/es/form';
  import SmartModuleDrawer from '/@/views/pages/smartModule/modules/smartModuleDrawer.vue';

  // import headerImg from '/@/assets/images/header.jpg';
  import manImg from '/@/assets/images/man.png';
  import womanImg from '/@/assets/images/woman.png';
  import { propTypes } from '/@/utils/propTypes';
  import { openWindow } from '/@/utils';
  import type { ValidationRule } from 'ant-design-vue/lib/form/Form';

  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';

  import PersonDrawer from '/@/layouts/default/header/components/user-dropdown/PersonDrawer.vue';
  import ChangeCurDeptCodeModal from '/@/layouts/default/header/components/user-dropdown/ChangeCurDeptCodeModal.vue';
  import CurRoleCodeModal from '/@/layouts/default/header/components/user-dropdown/CurRoleCodeModal.vue';
  import ChangePwdModal from '/@/layouts/default/header/components/user-dropdown/ChangePwdModal.vue';
  import ChangeMobileModal from '/@/layouts/default/header/components/user-dropdown/ChangeMobileModal.vue';
  import { useDrawer } from '/@/components/Drawer';
  import { getMyInfo, getShowImg } from '/@/api/system/system';
  import { useMessage } from '/@/hooks/web/useMessage';
  import md5 from 'crypto-js/md5';

  type MenuEvent = 'logout' | 'doc' | 'lock' | 'person' | 'dept' | 'role' | 'pwd' | 'mobile';

  export default defineComponent({
    name: 'UserDropdown',
    components: {
      Dropdown,
      Menu,
      MenuItem: createAsyncComponent(() => import('./DropMenuItem.vue')),
      MenuDivider: Menu.Divider,
      LockAction: createAsyncComponent(() => import('../lock/LockModal.vue')),
      PersonDrawer,
      ChangeCurDeptCodeModal,
      CurRoleCodeModal,
      ChangePwdModal,
      Tag,
      Modal,
      Row,
      Col,
      Form,
      FormItem: Form.Item,
      InputTextArea: Input.TextArea,
      Switch,
      Input,
      Tooltip,
      ChangeMobileModal,
      Icon,
      SmartModuleDrawer,
    },
    props: {
      theme: propTypes.oneOf(['dark', 'light']),
    },
    setup() {
      const { prefixCls } = useDesign('header-user-dropdown');
      const { t } = useI18n();
      const { getShowDoc, getUseLockPage } = useHeaderSetting();
      const userStore = useUserStore();

      const isDeptSwitchable = computed(() => userStore.getUserInfoPlus?.isDeptSwitchable);
      const isRoleSwitchable = computed(() => userStore.getUserInfoPlus?.isRoleSwitchable);
      const getUserInfo = computed(() => {
        const { realName = '', avatar, desc, gender, onDuty } = userStore.getUserInfo || {};
        return { realName, avatar: avatar || (gender ? womanImg : manImg), desc, onDuty };
      });

      const [register, { openModal }] = useModal();

      const onDutyVisible = ref(false);

      const formData = ref({
        isOnDuty: true,
        remark: '',
        isArchiveShowAsUserInfo: false,
        personId: -1,
        personVisitKey: '',
      });
      const { createMessage } = useMessage();
      const formRef = ref();
      const isOnDutyEnabled = ref(false);
      const isMobileLocked = ref(false);
      // 取系统中邮箱(263邮箱)
      let userEmail = '';
      // 取时间戳
      const timestamp = String(new Date().getTime());
      // 是否启用263邮箱
      const is263EmailEnabled = ref(false);

      function handleLock() {
        openModal(true);
      }

      //  login out
      function handleLoginOut() {
        userStore.confirmLoginOut();
      }

      // open doc
      function openDoc() {
        openWindow(DOC_URL);
      }

      const [registerDrawer, { openDrawer }] = useDrawer();
      const [registerPersonDrawer, { openDrawer: openPersonDrawer }] = useDrawer();
      // open person
      function handlePerson() {
        if (formData.value.isArchiveShowAsUserInfo) {
          openDrawer(true, {
            isUpdate: 2,
            record: {
              moduleCode: 'personbasic',
              id: formData.value.personId,
              visitKey: formData.value.personVisitKey,
            },
          });
        } else {
          openPersonDrawer(true, {
            isUpdate: true,
            record: userStore.getUserInfo || {},
          });
        }
      }

      //修改成功回调
      async function handlePersonCallback() {
        const info = await getMyInfo();
        isMobileLocked.value = info['isMobileLocked'];
        const userInfo = info['user'];
        userInfo.deptCode = info.deptCode;
        userInfo.deptName = info.deptName;
        console.log('handlePersonCallback userInfo', userInfo);
        if (info['portrait']) {
          await getShowImg({ path: info['portrait'] }).then((res: any) => {
            userInfo['avatar'] = bufToUrl(res);
          });
        }
        userStore.setUserInfo(userInfo);
        userStore.setUserInfoPlus(info);

        formData.value.isOnDuty = userInfo.onDuty;
        if (formData.value.isOnDuty) {
          formData.value.remark = '';
        } else {
          formData.value.remark = info['user'].remark;
        }
      }

      //更换部门
      const [registerCurDeptCode, { openModal: openCurDeptCodeModal }] = useModal();
      const handleCurDeptCodeCallback = () => {
        handlePersonCallback();
      };
      //更换角色
      const [registerCurRoleCode, { openModal: openCurRoleCodeModal }] = useModal();
      const handleCurRoleCodeCallback = () => {
        handlePersonCallback();
      };

      const [registerChangePwd, { openModal: openChangePwdModal }] = useModal();

      const [registerChangeMobile, { openModal: openChangeMobileModal }] = useModal();

      function handleMenuClick(e: { key: MenuEvent }) {
        switch (e.key) {
          case 'logout':
            handleLoginOut();
            break;
          case 'doc':
            openDoc();
            break;
          case 'lock':
            handleLock();
            break;
          case 'person':
            handlePerson();
            break;
          case 'dept':
            openCurDeptCodeModal(true, {});
            break;
          case 'role':
            openCurRoleCodeModal(true, {});
            break;
          case 'pwd':
            openChangePwdModal(true);
            break;
          case 'mobile':
            openChangeMobileModal(true);
        }
      }

      onMounted(async () => {
        const info = await getMyInfo();
        console.log('onMounted', info);
        is263EmailEnabled.value = info.is263EmailEnabled;
        userEmail = info['user'].email;
        formData.value.isArchiveShowAsUserInfo = info.isArchiveShowAsUserInfo;
        formData.value.personId = info.personId;
        formData.value.personVisitKey = info.personVisitKey;
        formData.value.isOnDuty = info['user'].onDuty;
        isOnDutyEnabled.value = info.isOnDutyEnabled;
        if (formData.value.isOnDuty) {
          formData.value.remark = '';
        } else {
          formData.value.remark = info['user'].remark;
        }
      });

      const handleOnDuty = async () => {
        onDutyVisible.value = true;
      };

      function handleCancel() {
        onDutyVisible.value = false;
      }

      function handleClickEmail() {
        // 263邮箱sign
        const emailSign = md5(
          '2A!^fu' + 'windows' + 'READMAIL' + '100404' + 'yfgc.ccxict.cn' + userEmail + timestamp,
        ).toString();
        window.open(
          'http://weixin.263.net/partner/web/third/mail/loginMail.do?loginPlatform=windows&type=READMAIL&partnerid=100404&authcorpid=yfgc.ccxict.cn&userid=' +
            userEmail +
            '&timestamp=' +
            timestamp +
            '&sign=' +
            emailSign,
          '_blank',
        );
      }

      async function handleSubmit() {
        const data = await formRef.value.validate();
        console.log('handleSubmit data', data);
        if (!data) return;

        if (!data.remark) {
          data.remark = ' ';
        }

        await onDuty(formData.value);
        createMessage.success('操作成功');
        getUserInfo.value.onDuty = formData.value.isOnDuty;
        onDutyVisible.value = false;
        // formRef.value.resetFields();
      }

      const rules: Record<string, Rule[]> = {
        remark: [{ required: true, message: '请输入原因', trigger: 'change' }],
      };

      const handleSuccess = () => {
        createMessage.success('操作成功');
      };

      return {
        prefixCls,
        t,
        getUserInfo,
        handleMenuClick,
        getShowDoc,
        register,
        getUseLockPage,
        registerPersonDrawer,
        handlePersonCallback,
        registerCurDeptCode,
        handleCurDeptCodeCallback,
        registerCurRoleCode,
        handleCurRoleCodeCallback,
        isDeptSwitchable,
        isRoleSwitchable,
        registerChangePwd,
        handleOnDuty,
        handleCancel,
        onDutyVisible,
        formData,
        handleSubmit,
        rules,
        formRef,
        isOnDutyEnabled,
        registerChangeMobile,
        handleClickEmail,
        is263EmailEnabled,
        registerDrawer,
        handleSuccess,
      };
    },
  });
</script>
<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-header-user-dropdown';

  .@{prefix-cls} {
    height: @header-height;
    padding: 0 0 0 10px;
    padding-right: 10px;
    overflow: hidden;
    font-size: 12px;
    cursor: pointer;
    align-items: center;

    img {
      width: 24px;
      height: 24px;
      margin-right: 12px;
    }

    &__header {
      border-radius: 50%;
    }

    &__name {
      font-size: 14px;
    }

    &--dark {
      &:hover {
        background-color: @header-dark-bg-hover-color;
      }
    }

    &--light {
      &:hover {
        background-color: @header-light-bg-hover-color;
      }

      .@{prefix-cls}__name {
        color: @text-color-base;
      }

      .@{prefix-cls}__desc {
        color: @header-light-desc-color;
      }
    }

    &-dropdown-overlay {
      .ant-dropdown-menu-item {
        min-width: 160px;
      }
    }
  }
</style>
